package com.ruicar.afs.cloud.afscase.channel.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.channel.common.Constants;
import com.ruicar.afs.cloud.afscase.channel.condition.DrawerPartyCondition;
import com.ruicar.afs.cloud.afscase.channel.entity.Blacklist;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelCoopeDrawerParty;
import com.ruicar.afs.cloud.afscase.channel.entity.DrawerParty;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelCoopeDrawerPartyService;
import com.ruicar.afs.cloud.afscase.channel.service.DrawerPartyService;
import com.ruicar.afs.cloud.afscase.channel.utils.BlackDic;
import com.ruicar.afs.cloud.afscase.channel.vo.DrawerPartyVo;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: sang jian
 * @date: 2020/5/25 14:05
 * @description:
 */
@RestController
@AllArgsConstructor
@RequestMapping("/drawerParty")
public class DrawerPartyController {

    @Autowired
    private DrawerPartyService drawerPartyService;

    @Autowired
    private ChannelCoopeDrawerPartyService channelCoopeDrawerPartyService;

    @Autowired
    private ChannelBaseInfoService channelBaseInfoService;

    @PostMapping("/getByCondition")
    @ApiOperation(value = "多条件分页获取开票方")
    public IResponse<IPage<DrawerPartyVo>> getDrawerPartys(@RequestBody DrawerPartyCondition condition) {

        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<DrawerPartyVo> list = drawerPartyService.getDrawerPartyList(page, condition);
        return IResponse.success(list);
    }

    @GetMapping("/getDrawerPartyById/{id}/{carDealerId}")
    @ApiOperation(value = "根据开票方id查询基本信息")
    public IResponse getDrawerPartyById(@PathVariable String id, @PathVariable String carDealerId) {
        DrawerParty drawerParty = drawerPartyService.getById(id);
        List<ChannelCoopeDrawerParty> channelCoopeDrawerParties = channelCoopeDrawerPartyService.list(Wrappers.<ChannelCoopeDrawerParty>query().lambda()
                .eq(ChannelCoopeDrawerParty::getDrawerId, id)
                .eq(ChannelCoopeDrawerParty::getCardealerId, carDealerId)
        );
        List list = new ArrayList();
        list.add(drawerParty);
        list.add(channelCoopeDrawerParties.get(0));
        return IResponse.success(list);
    }

    @GetMapping("/disableDrawerParty/{ids}")
    @ApiOperation(value = "禁用开票方")
    public IResponse disableDrawerParty(@PathVariable String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            DrawerParty party = drawerPartyService.getById(ids[i]);
            party.setStatus(Constants.DISABLE);
            boolean result = drawerPartyService.updateById(party);
            if (!result) {
                return IResponse.fail("第" + (i + 1) + "个开票方停用失败");
            }
        }
        return IResponse.success("操作成功");
    }

    @DeleteMapping("/delByIds/{id}")
    @ApiOperation(value = "删除开票方")
    @Transactional(rollbackFor = Exception.class)
    public IResponse deleteById(@PathVariable String id) {
        List<ChannelCoopeDrawerParty> list = channelCoopeDrawerPartyService.list(Wrappers.<ChannelCoopeDrawerParty>query().lambda().eq(ChannelCoopeDrawerParty::getDrawerId, id));
        if (list != null && list.size() > 0) {
            for (ChannelCoopeDrawerParty temp : list) {
                channelCoopeDrawerPartyService.removeById(temp.getId());
            }
        }
        boolean result = drawerPartyService.removeById(id);
        return result ? IResponse.success("删除成功") : IResponse.fail("删除失败");
    }


    @GetMapping("/getCarDealerByChannelId/{id}")
    @ApiOperation(value = "根据渠道id查询车商信息")
    public IResponse<DrawerPartyVo> getCarDealerByChannelId(@PathVariable String id) {
        ArrayList<DrawerPartyVo> list = drawerPartyService.getCarDealerByChannelId(id);
        return IResponse.success(list);
    }

    @GetMapping("/getChannelNameByChannelId/{id}")
    @ApiOperation(value = "根据渠道id查询渠道信息")
    public IResponse<String> getChannelNameByChannelId(@PathVariable String id) {
        String channelName = drawerPartyService.getChannelNameByChannelId(id);
        return IResponse.success(channelName);
    }


    @PostMapping("/saveOrUpdateDrawerParty")
    @ApiOperation(value = "新增或更新开票方")
    @Transactional(rollbackFor = Exception.class)
    public IResponse saveOrUpdateDrawerParty(@RequestBody DrawerPartyCondition condition) {
        DrawerParty drawerParty = condition.getDrawerParty();
        ChannelCoopeDrawerParty channelCoopeDrawerParty = condition.getChannelCoopeDrawerParty();
        List list = new ArrayList();

        List<DrawerParty> drawerPartyList = drawerPartyService.list(Wrappers.<DrawerParty>query().lambda()
                .eq(DrawerParty::getDrawerPartyName, drawerParty.getDrawerPartyName()));
        //有这家开票方
        if (CollectionUtils.isNotEmpty(drawerPartyList)) {
            for (int i = 0; i < drawerPartyList.size(); i++) {
                List<ChannelCoopeDrawerParty> parties = channelCoopeDrawerPartyService.list(Wrappers.<ChannelCoopeDrawerParty>query().lambda()
                        .eq(ChannelCoopeDrawerParty::getCardealerId, channelCoopeDrawerParty.getCardealerId())
                        .eq(ChannelCoopeDrawerParty::getDrawerId, drawerPartyList.get(i).getId())
                );
                if (CollectionUtils.isNotEmpty(parties) && drawerParty.getId()==null) {
                        return IResponse.fail("该车商已与该开票方关联");
                }
            }
        }

        //更新的情况
        if (drawerParty.getId() != null) {
            //判断这个车商是否已经跟这家开票方存在关联关系
            boolean result = drawerPartyService.updateById(drawerParty);
            boolean result2 = channelCoopeDrawerPartyService.updateById(channelCoopeDrawerParty);
            list.add(drawerParty);
            list.add(channelCoopeDrawerParty);
            return result && result2 ? IResponse.success(list) : IResponse.fail("操作失败");
        }

        //没有这家开票方的情况
        boolean result1 = drawerPartyService.saveOrUpdate(drawerParty);
        list.add(drawerParty);
        //保存到中间表
        channelCoopeDrawerParty.setDrawerId(drawerParty.getId());
        boolean result2 = channelCoopeDrawerPartyService.saveOrUpdate(channelCoopeDrawerParty);
        list.add(channelCoopeDrawerParty);
        if (result1 && result2) {
            return IResponse.success(list);
        }
        return IResponse.fail("保存失败");
    }


    @PostMapping("/getAllSPChannels")
    @ApiOperation(value = "查询所有的SP和总对总")
    public IResponse getAllSPChannels(@RequestBody DrawerPartyCondition condition) {
        List list = new ArrayList();
        list.add(Constants.SP);
        list.add(Constants.TOTAl);
        List<ChannelBaseInfo> channelBaseInfos = new ArrayList<>();
        if(condition.getChannelBelong() != null){
            if(condition.getChannelBelong().size() == 2){
                //普通
                channelBaseInfos =  channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                        .in(ChannelBaseInfo::getChannelBelong,list)
                        .eq(ChannelBaseInfo::getChannelType,Constants.CHANNEL)
                        .and(wrapper1 -> wrapper1.eq(ChannelBaseInfo::getChannelStatusOldCar, Constants.ENABLED)
                                .or(wrapper2 -> wrapper2.eq(ChannelBaseInfo::getChannelStatus, Constants.ENABLED))
                        )
                );

            }else if(condition.getChannelBelong().size() == 1){
                //直营
                channelBaseInfos =  channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                        .eq(ChannelBaseInfo::getChannelBelong,Constants.DIRECT)
                        .eq(ChannelBaseInfo::getChannelType,Constants.CHANNEL)
                        .and(wrapper1 -> wrapper1.eq(ChannelBaseInfo::getChannelStatusOldCar, Constants.ENABLED)
                                .or(wrapper2 -> wrapper2.eq(ChannelBaseInfo::getChannelStatus, Constants.ENABLED))
                        )
                );
            }
        }else{
                channelBaseInfos =  channelBaseInfoService.list(Wrappers.<ChannelBaseInfo>query().lambda()
                        .eq(ChannelBaseInfo::getChannelType,Constants.CHANNEL)
                        .and(wrapper1 -> wrapper1.eq(ChannelBaseInfo::getChannelStatusOldCar, Constants.ENABLED)
                                .or(wrapper2 -> wrapper2.eq(ChannelBaseInfo::getChannelStatus, Constants.ENABLED))
                        )
                );

           /* QueryWrapper<ChannelBaseInfo> channelBaseInfoTempQueryWrapper = new QueryWrapper<>();
            channelBaseInfoTempQueryWrapper.eq("channel_type", Constants.CHANNEL);
            channelBaseInfoTempQueryWrapper.in("channel_belong", list);
            channelBaseInfoTempQueryWrapper.and(wrapper -> wrapper.eq("channel_status", Constants.ENABLED).or().eq("channel_status_old_car", Constants.ENABLED));
             channelBaseInfos = channelBaseInfoService.list(channelBaseInfoTempQueryWrapper);*/

        }
        return IResponse.success(channelBaseInfos);
    }


    @PostMapping("/getDrawerPartyByChannel")
    @ApiOperation(value = "查询合作商下的开票方列表")
    public IResponse getDrawerPartyByChannel(@RequestBody DrawerPartyCondition condition) {
        if (StringUtils.isBlank(condition.getDrawerPartyName()) || StringUtils.isBlank(condition.getChannelId())) {
            return IResponse.fail("开票方名称或合作商id为空");
        }
        return drawerPartyService.getDrawerPartyByChannel(condition);
    }


    @PostMapping("/getDrawerPartyByIdType")
    @ApiOperation(value = "通过纳税人识别号查询开票方")
    public IResponse getDrawerPartyByTaxpayer(@RequestBody Blacklist blacklist) {
        List<DrawerParty> list = drawerPartyService.list(Wrappers.<DrawerParty>query().lambda().eq(DrawerParty::getTaxpayerIdNumber, blacklist.getIdCode()));
        List<DrawerParty> list2 = drawerPartyService.list(Wrappers.<DrawerParty>query().lambda().eq(DrawerParty::getDrawerPartyName, blacklist.getBlackName()));
        if(list2.size()>0){
            for(int i = 0; i < list2.size(); i++){
                list.add(list2.get(i));
            }
        }
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setStatus(BlackDic.STATUS_STOP);
                drawerPartyService.updateById(list.get(i));
            }
        }
        return new IResponse().setData(list).setMsg("查询成功");
    }


    @PostMapping(value = "/upStatusDrawerByChannelIdsPass")
    @ApiOperation(value = "黑名单根据id启用开票方")
    public IResponse upStatusDrawerByChannelIdsPass(@RequestBody List<Long> ids) {
        //截取字符串
        if (ids.size() > 0) {
            for (int j = 0; j < ids.size(); j++) {
                DrawerParty channel = drawerPartyService.getById(ids.get(j));
                if (channel != null) {
                    channel.setStatus(BlackDic.STATUS_PASS);
                    channel.setUpdateTime(new Date(System.currentTimeMillis()));
                    channel.setUpdateBy(SecurityUtils.getUsername());
                    boolean result = drawerPartyService.updateById(channel);
                    if (!result) {
                        return IResponse.fail("状态更新失败！");
                    }
                }
            }
        }
        return new IResponse<Boolean>().setMsg("状态更新成功");
    }


    @PostMapping(value = "/getdrawerPartyByChannelId")
    @ApiOperation(value = "根据渠道id查询关联的开票方")
    public IResponse getdrawerPartyByChannelId(@RequestBody DrawerPartyCondition condition) {

        String channelId = condition.getChannelId();
        Assert.isTrue(StringUtils.isNotBlank(channelId),"合作商的id为空,查询失败!");
        List<DrawerParty> drawerPartyList = new ArrayList<>();
        List<ChannelCoopeDrawerParty> coopeDrawerParties = channelCoopeDrawerPartyService.list(Wrappers.<ChannelCoopeDrawerParty>query().lambda()
                .eq(ChannelCoopeDrawerParty::getChannelId, channelId));
        if(coopeDrawerParties.size() > 0){
            for (ChannelCoopeDrawerParty coopeDrawerParty : coopeDrawerParties){
                List<DrawerParty> drawerParty = drawerPartyService.list(Wrappers.<DrawerParty>query().lambda()
                        .eq(DrawerParty::getId, coopeDrawerParty.getDrawerId())
                        .like(StringUtils.isNotBlank(condition.getDrawerPartyName()), DrawerParty::getDrawerPartyName, condition.getDrawerPartyName())
                );
                drawerPartyList.addAll(drawerParty);
            }
        }
        return IResponse.success(drawerPartyList);
    }

}
